<?php

/**
 * Description of SoBizFinanceAccount
 *
 * @author Alen
 * @since 1.0.0 2014-3-22
 */
class SoBizFinanceAccount extends SoBizBase {

    //put your code here
    public function __construct() {
        parent::__construct();
        $this->dm->tablename = 'tfinanceaccount';
    }

    /**
     * 查询一条记录
     * @param type $uname
     * @param type $search
     * @return type
     * @since 1.0.0 2013-12-16 sutroon
     */
    public function read_one($uname, $search = 'UserName=\'%s\'') {
        $rs = $this->dm->select_one_row('', sprintf($search, $uname));
        if (!$rs) 
            $this->dm->insert_record('', 'UserName,Blance,FrozenBlance,Remark,`State`', '\'' . $uname . '\',0,0,\'系统查询创建账户\',1', '');
        return $rs ? $rs : array('Blance' => 0, 'FrozenBlance' => 0, 'State' => 1);
    }

    /**
     * 获取分页数据
     * @param type $pager_text
     * @param type $dataset
     * @param type $pageid
     * @param type $keyword
     * @since 1.0.0 2012-12-11 sutroon
     * @example 
      $page_text='';
      $dataset=null;
      $biz->get_paging_data($pager_text, $dataset, request_numeric('page'), request_string('keyword'));
     */
    public function get_paging_data(&$pager_text, &$dataset, $pageid, $keyword) {
        // 获取分页数据
        $pager = new SoDataPager($pageid);
        $sqlc = $keyword ? " where UserName like '%$keyword%'" : '';
        $dataset = $this->dm->select_pagingset($pager->pageid, $pager->pagesize, $pager->recordcount, 'tfinanceaccount ' . $sqlc, 'CreatedTime desc', '*');
        $pager->set_dataset($dataset, $pager->recordcount);
        $pager_text = $pager->get_pager_text(set_url_param(array('page' => '.pageid.')));
    }

    /**
     * 获取会员可用总金额
     * @since 1.0.0 2013-12-14
     */
    public function get_amount_all() {
        return $this->dm->select_value('tfinanceaccount', 'UserName <> \'system\'', 'sum(Blance)', '0.00');
    }

    /**
     * 获取会员总不可用余额
     * @since 1.0.0 2013-12-14
     */
    public function get_amount_frozenblance() {
        return $this->dm->select_value('tfinanceaccount', 'UserName <> \'system\'', 'sum(FrozenBlance)', '0.00');
    }

    /**
     * 获取System可用余额
     * @since 1.0.0 2013-12-14
     */
    public function get_amount_system() {
        return $this->dm->select_value('tfinanceaccount', 'UserName=\'system\'', 'sum(Blance)', '0.00');
    }

    /**
     * 获取购买坐席提成金额
     * @since 1.0.0 2013-12-14
     */
    public function get_amount_comission() {
        return $this->dm->select_value('tfinancetransactionlog', 'TransactionType=\'IN_PREORDER_SEAT_COMMISSION\' and UserName <> \'system\'', 'sum(Amount)', '0.00');
    }

    /**
     * 获取账户状态
     * @param type $uname
     * @return type
     * @since 1.0.0 2013-12-14
     */
    public function get_state($uname) {
        return $this->dm->select_value('tfinanceaccount', 'UserName=\'' . $uname . '\'', 'State');
    }

    /**
     * 更新账户状态
     * @param type $uname
     * @param type $state
     * @return string
     * @since 1.0.0 2013-12-14 sutroon
     */
    public function update_state($uname, $state) {
        if (!$sn)
            return '参数无效';
        $this->dm->add_param('State', $state, 'int');
        return $this->dm->update(sprintf('UserName=\'%s\'', $uname)) ? 'SUCCESS' : $this->dm->get_error();
    }

    /**
     * 添加一条交易(直接操作可用余额)
     * @param type $uname
     * @param type $amount
     * @param type $transtype
     * @return string
     * @since 1.0.0 2013-12-17 sutroon
     */
    public function add_transaction($uname, $amount, $transtype) {
        if (strlen($transtype) == 0)
            return '交易类型无效';
        $acc = $this->read_one($uname);
        if (substr($transtype, 0, 3) == 'IN_') {
            $acc['Blance'] = $acc['Blance'] + $amount;
        } else {
            $acc['Blance'] = $acc['Blance'] - $amount;
            if ($acc['Blance'] < 0)
                return '余额不足';
        }
        $this->dm->insert_record('tfinancetransactionlog', 'SerialNo,Amount,TransactionType,Blance,UserName,State,ModifiedTime', sprintf("'%s',%u,'%s',%u,'%s',1,'%s'", get_serialstring(), $amount, $transtype, $acc['Blance'], $uname, date('Y-m-d H:i:s')));
        $this->dm->update_records('', sprintf("Blance=%u, ModifiedTime='%s'", $acc['Blance'], date('Y-m-d H:i:s')), "UserName='$uname'");
        return 'SUCCESS';
    }

    /**
     * 预购席位付款
     * @param type $uname
     * @param type $amount
     * @return string
     * @since 1.0.0 2013-12-17
     */
    function add_transaction_for_prevorderseat($uname, $amount) {
        $acc = $this->read_one($uname);
        $acc['Blance'] = $acc['Blance'] - $amount;
        if ($acc['Blance'] < 0)
            return '余额不足';
        $this->dm->insert_record('tfinancetransactionlog', 'SerialNo,Amount,TransactionType,Blance,UserName,State,ModifiedTime', sprintf("'%s',%u,'OUT_PREORDER_SEAT',%u,'%s',1,'%s'", get_serialstring(), $amount, $acc['Blance'], $uname, date('Y-m-d H:i:s')));
        $this->dm->update_records('', sprintf("Blance=Blance-%u,AdvancePayment=AdvancePayment+%u,ModifiedTime='%s'", $amount, $amount, date('Y-m-d H:i:s')), "UserName='$uname'");
        return 'SUCCESS';
    }

    /**
     * 激活预购席位
     * @param type $uname
     * @param type $amount
     * @return string
     * @since 1.0.0 2013-12-17
     */
    public function add_transaction_for_activeorderseat($uname, $amount) {
        $this->dm->update_records('', sprintf("AdvancePayment=AdvancePayment-%u, ModifiedTime='%s'", $amount, date('Y-m-d H:i:s')), "UserName='$uname'");
        return 'SUCCESS';
    }

    /**
     * 支付给5级代理 100,50,30,20,10
     * @param type $uname
     * @param type $years
     * @param type $arr
     * @return int
     * @since 1.0.0 2013-12-17
     */
    public function pay_to_agent($uname, $years = 1, $arr = array(100, 50, 30, 20, 10)) {
        $refername = $this->dm->select_value('tusermember', "UserName='$uname'", 'ReferrerName');
        if (!$refername)
            return 0;
        $remain = 300 * $years;
        // level 1
        $refername = $this->pay_to_agent_func($uname, $refername, $remain, 100, $years, 1);
        if (!$refername)
            return 1;
        // level 2
        $refername = $this->pay_to_agent_func($uname, $refername, $remain, 50, $years, 2);
        if (!$refername)
            return 2;
        // level 3
        $refername = $this->pay_to_agent_func($uname, $refername, $remain, 30, $years, 3);
        if (!$refername)
            return 3;
        // level 4
        $refername = $this->pay_to_agent_func($uname, $refername, $remain, 20, $years, 4);
        if (!$refername)
            return 4;
        // level 5
        $refername = $this->pay_to_agent_func($uname, $refername, $remain, 10, $years, 5);
        // remain to system
        if ($remain > 0) {
            $refername = 'system';
            $acc = $this->read_one($refername);
            $amount = $remain;
            $acc['Blance'] = $acc['Blance'] + $amount;
            $this->dm->insert_record('tfinancetransactionlog', 'SerialNo,Amount,TransactionType,Blance,UserName,State,ModifiedTime,AdminRemark', sprintf("'%s',%u,'IN_COMMISSION',%u,'%s',1,'%s','您的%d级[%s]代理开通代理服务%d年，向您支付提成%u元'", get_serialstring(), $amount, $acc['Blance'], $refername, date('Y-m-d H:i:s'), 5, $uname, $years, $amount));
            $this->dm->update_records('tfinanceaccount', sprintf("Blance=%u, ModifiedTime='%s'", $acc['Blance'], date('Y-m-d H:i:s')), sprintf("UserName='%s'", $refername));
        }
    }

    private function pay_to_agent_func($uname, $refername, &$remain, $commition, $years, $i) {
        if (!$refername)
            return '';
        $u = $this->dm->select_one_row('tusermember', sprintf("UserName='%s'", $refername), 'IsAgent,ReferrerName');
        if (!$u)
            return '';
        if ($u['IsAgent']) {
            $acc = $this->read_one($refername);
            if ($acc['State']) {
                if ($refername == 'system') {
                    $amount = $remain;
                    $remain = 0;
                } else {
                    $amount = $commition * $years;
                    $remain-=$amount;
                }
                $acc['Blance'] = $acc['Blance'] + $amount;
                $this->dm->insert_record('tfinancetransactionlog', 'SerialNo,Amount,TransactionType,Blance,UserName,State,ModifiedTime,AdminRemark', sprintf("'%s',%u,'IN_COMMISSION',%u,'%s',1,'%s','您的%d级[%s]代理开通代理服务%d年，向您支付提成%u元'", get_serialstring(), $amount, $acc['Blance'], $refername, date('Y-m-d H:i:s'), $i, $uname, $years, $amount));
                $this->dm->update_records('tfinanceaccount', sprintf("Blance=%u, ModifiedTime='%s'", $acc['Blance'], date('Y-m-d H:i:s')), sprintf("UserName='%s'", $refername));
            }
        }
        return $u['ReferrerName'];
    }

}
